package com.sry.blog.sys.controller;

import cn.hutool.core.util.StrUtil;
import com.sry.blog.common.api.CommonResult;
import com.sry.blog.dto.LoginDTO;
import com.sry.blog.enums.CheckToken;
import com.sry.blog.enums.Exist;
import com.sry.blog.sys.model.User;
import com.sry.blog.sys.service.UserService;
import com.sry.blog.utils.MD5Util;
import com.sry.blog.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Random;

@RestController
@Slf4j
public class LoginController {
    @Autowired
    private UserService userService;

    private String salt = MD5Util.setSalt(5 + new Random().nextInt(5));

    /**
     * 用户登录（可以通过邮箱，手机号，用户名登录）
     *
     * @param uname,password 账号，密码
     * @return LoginDTO（用户信息+token）
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<LoginDTO> login(@RequestParam String uname, @RequestParam String password) {
        User user = User.builder().userName(uname).password(password).phone(uname).email(uname).build();
        user = userService.getUser(user);
        if (user == null) {
            return CommonResult.failed("没有该用户，请注册新用户");
        }
        log.info(user.toString());
        String salt = user.getSalt();
        try {
            if (StrUtil.equals(MD5Util.setPassword(password, salt), user.getPassword())) {
                Date date = new Date();
                user.setRecentLogin(date);
                userService.creatOrUpdate(user);
                final String userName = user.getUserName();
                LoginDTO loginDTO = LoginDTO.builder().user(user).token(TokenUtil.token(userName, password)).build();
                log.info("{}-----{}登录成功", date, userName);
                return CommonResult.success(loginDTO, "登录成功");
            } else {
                return CommonResult.loginFailed();
            }
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return CommonResult.failed();
    }

    /**
     * 判断User是否存在
     *
     * @param user 主要是userName email phone
     * @return CommonResult
     */
    @RequestMapping(value = "/exist", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult isExist(@RequestBody User user) {
        Exist exist = userService.isExist(user);
        return CommonResult.success(exist.getCode(), exist.getMsg());
    }

    /**
     * 验证Token
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/token", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult isToken(@RequestParam String token) {
        CheckToken checkToken = TokenUtil.verifyToken(token);
        if (checkToken.getCode() == 200) {
            return CommonResult.success(checkToken);
        } else {
            return CommonResult.failed(checkToken);
        }
    }

}
